# -*- coding: utf-8 -*-
'''
u115 bot

@author: deadblue
'''

from cn._2dland import net
import logging
import re
import simplejson
import time

class AlreadyPickedException(Exception):
    def __init__(self):
        pass

class u115bot(object):

    ''' 登录API '''
    API_LOGIN_URL = 'https://passport.115.com/?ac=login'
    ''' 获取领取空间的token '''
    API_TOKEN_URL = 'http://115.com/?ct=file&ac=userfile&aid=1&cid=0&tpl=list_pg&limit=28'
    ''' 领取空间API '''
    API_PICKUP_URL = 'http://115.com/?ct=ajax_user&ac=pick_space&token=%s&_=%d'

    def __init__(self, username, password):
        self.client = net.HttpClient()
        self.username = username
        self.password = password

        self.is_login = False

    def login(self):
        ''' 登录到 115 '''
        try :
            resp = self.client.post(self.API_LOGIN_URL, 
                                    {'login[account]': self.username, 'login[passwd]': self.password,
                                     'login[time]': 'on', 'back': 'http://www.115.com', 'goto': 'http://115.com'}, 
                                    'http://www.115.com/')
            logging.debug(resp.status_code)
            if resp.status_code == 200:
                # 检查响应头中是否有Set-Cookie
                # 有则认为登录成功
                #self.is_login = True
                self.is_login = resp.headers.has_key('Set-Cookie')
        except :
            self.is_login = False
        return self.is_login

    def get_token(self):
        ''' 获取领取空间的token '''
        token = None
        try :
            resp = self.client.get(self.API_TOKEN_URL)
            p = re.compile(r"take_token: '\w+?'")
            m = p.search(resp.content)
            if not m is None:
                token = m.group()[13:-1]
        except :
            token = None
        return token

    def pick(self):
        ''' 领取空间 '''
        picked = -1
        try :
            token = self.get_token()
            if token is None:
                raise AlreadyPickedException()

            url = self.API_PICKUP_URL % (token, time.time())
            resp = self.client.get(url)
            if resp.status_code != 200:
                raise Exception('http error')

            jsobj = simplejson.loads(resp.content)
            if not jsobj['state']:
                raise Exception('pick failed')
            picked = jsobj['picked_num']
        except AlreadyPickedException :
            picked = 0
        except :
            picked = -1
        return picked

    def renew(self):
        ''' 文件续期 '''
        state = False
        try :
            url = 'http://u.115.com/?ct=ajax_file&ac=share&is_share=2&aid=1&cid=0&is_batch=1&_=%d' % (time.time())
            resp = self.client.get(url)
            if resp.status_code != 200:
                raise Exception('http errrrrrrrr')
            jsObj = simplejson.loads(resp.content)
            state = jsObj['state']
        except :
            state = False
        return state
